package com.wdc.queue;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Queue;

public class ArrayQueue1<E>{

    private E[] array;
    private int head = 0;
    private int tail = 0;

    //带参构造初始化队列容量
    public ArrayQueue1(int capacity) {
        //数组大小是期望的容量 +1
        array = (E[]) new Object[capacity+1];

    }

    /**
     * 判断队列是否是空的
     * @return
     */
    public boolean isEmpty(){

        return head == tail;
    }

    /**
     * 判断队列是否是满的
     * @return
     */
    public boolean isFull(){
        return (tail + 1) % array.length == head ;
    }

    /**
     * 向队列尾部新增元素
     * @return
     */
    public boolean offer(E value){
        if (isFull()) {
            return false;
        }
        array[tail] = value;
        tail  = (tail + 1) % array.length;
        return true;
    }

    /**
     * 从队列头部移除元素
     * @return
     */
    public E poll(){
        if (isEmpty()) {
            return null;
        }
        E poll = array[head];
        head = (head + 1) % array.length;
        return poll;

    }

    /**
     * 获取队列头部元素
     * @return
     */
    public E peek(){
        if (isEmpty()) {
            return null;
        }
        E value = array[head];
        return value;

    }

    public Iterator<E> iterator(){
        return new Iterator<E>() {
            int p = head;
            @Override
            public boolean hasNext() {

                return p != tail;
            }

            @Override
            public E next() {
                E value = array[p];
                p = (p+1) % array.length;
                return value;
            }
        };
    }


    public static void main(String[] args) {
        ArrayQueue1<Integer> queue = new ArrayQueue1<>(3);
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);

        Iterator<Integer> iterator = queue.iterator();
        while (iterator.hasNext()){
            Integer next = iterator.next();
            System.out.println(next);
        }


    }


}
